#include <iostream>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <thread>

int sockfd = -1;
std::string severip;
uint16_t severport;

void InitClint(const std::string &severip, uint16_t severport)
{
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "create socket error!\n"
                  << std::endl;
    }
}

void reaver()
{
    while (true)
    {

        // 读取
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        int m = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&temp, &len);
        if (m > 0)
        {
            buffer[m] = 0;
            //向2号文件(标准错误中打印)
            std::cerr << buffer << std::endl;
        }
    }
}

void sender()
{
    struct sockaddr_in sever;
    memset(&sever, 0, sizeof(sever));
    sever.sin_family = AF_INET;
    sever.sin_port = htons(severport);
    sever.sin_addr.s_addr = inet_addr(severip.c_str());

    while (true)
    {
        // 客户端输入数据
        std::cout << "please enter# ";
        std::string line;
        std::getline(std::cin, line);

        // 写入
        sendto(sockfd, line.c_str(), line.size(), 0,
               (struct sockaddr *)&sever, sizeof(sever));
    }
}

void Usage(std::string proc)
{
    std::cerr << "Usage: " << "+ sever_ip " << "+ sever_port" << std::endl;
}
//./udpclint sever_ip sever_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    severip = argv[1];
    severport = std::stoi(argv[2]);
    // 创建一个套接字
    InitClint(severip, severport);

    // 创建两个线程
    std::thread treav(reaver);
    std::thread tsend(sender);

    // 线程等待
    treav.join();
    tsend.join();

    return 0;
}